package com.hotel.user.controller;

import com.hotel.common.entity.User;
import com.hotel.common.utils.Result;
import com.hotel.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result<Long> register(@RequestBody User user) {
        return userService.register(user);
    }

    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable("id") Long id) {
        return userService.getUserById(id);
    }

    @GetMapping("/username/{username}")
    public Result<User> getUserByUsername(@PathVariable("username") String username) {
        return userService.getUserByUsername(username);
    }

    @GetMapping
    public Result<Map<String, Object>> getAllUsers(
            @RequestParam(name = "page", defaultValue = "1") int page,
            @RequestParam(name = "size", defaultValue = "10") int size,
            @RequestParam(name = "search", required = false) String search) {
        if (search != null && !search.trim().isEmpty()) {
            return userService.searchUsersByUsername(search.trim(), page, size);
        }
        return userService.getAllUsersWithPagination(page, size);
    }

    @PostMapping
    public Result<Long> createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @PutMapping
    public Result<Void> updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable("id") Long id) {
        return userService.deleteUser(id);
    }

    @PostMapping("/{userId}/roles/{roleId}")
    public Result<Void> assignRole(@PathVariable("userId") Long userId, @PathVariable("roleId") Long roleId) {
        return userService.assignRole(userId, roleId);
    }

    @DeleteMapping("/{userId}/roles/{roleId}")
    public Result<Void> removeRole(@PathVariable("userId") Long userId, @PathVariable("roleId") Long roleId) {
        return userService.removeRole(userId, roleId);
    }

    @GetMapping("/roles")
    public Result<List<User>> getUsersWithRoles() {
        return userService.getUsersWithRoles();
    }

    @PostMapping("/roles")
    public Result<Void> assignRolesToUser(@RequestBody Map<String, Object> request, 
                                        jakarta.servlet.http.HttpServletRequest httpRequest) {
        Long userId = Long.valueOf(request.get("userId").toString());
        @SuppressWarnings("unchecked")
        List<Integer> roleIdsInt = (List<Integer>) request.get("roleIds");
        List<Long> roleIds = roleIdsInt.stream()
                .map(Integer::longValue)
                .collect(java.util.stream.Collectors.toList());
        
        // 从请求头获取当前用户ID（由网关或拦截器设置）
        String currentUserIdStr = httpRequest.getHeader("X-User-Id");
        if (currentUserIdStr == null) {
            return Result.error("未获取到当前用户信息");
        }
        Long currentUserId = Long.valueOf(currentUserIdStr);
        
        return userService.assignRolesToUserWithPermission(currentUserId, userId, roleIds);
    }

    @DeleteMapping("/{userId}/roles")
    public Result<Void> removeAllRolesFromUser(@PathVariable("userId") Long userId) {
        return userService.removeAllRolesFromUser(userId);
    }
}